package com.mikewoo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Title: DiscardServer.java
 * Description: netty实现的服务端 
 * 
 * author     Phantom
 * date       2016年5月20日 上午11:07:34
 * @version    1.0.0
 */
public class DiscardServer {
	private int port;

	public DiscardServer(int port) {
		super();
		this.port = port;
	}
	
	public void run() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
			ServerBootstrap b = new ServerBootstrap(); // (2)
			b.group(bossGroup, workerGroup) //
			.channel(NioServerSocketChannel.class) // (3)
			.childHandler(new MyChannelInitializer())
			.option(ChannelOption.SO_BACKLOG, 128)          // (5)
			.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
			
			ChannelFuture f = b.bind(port).sync(); // (7)
			
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			 workerGroup.shutdownGracefully();
	         bossGroup.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
        int port = 8999;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8999;
        }
        new DiscardServer(port).run();
    }
}
